package com.fat.service.impl;

import com.fat.mapper.ArticleMapper;
import com.fat.pojo.Article;
import com.fat.pojo.Result;
import com.fat.pojo.vo.PageBean;
import com.fat.service.ArticleService;
import com.fat.utils.ThreadLocalUtil;
import com.github.pagehelper.PageHelper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;
import java.util.Objects;

@Service
public class ArticleServiceImpl implements ArticleService {

    @Autowired
    private ArticleMapper articleMapper;

    @Override
    public Result add(Article article) {
        //获取当前登录用户的信息
        Map<String, Object> map = ThreadLocalUtil.get();
        article.setCreateUser(Integer.parseInt(map.get("id").toString()));
        //新增文章
        int i = articleMapper.add(article);
        return i > 0 ? Result.success("新增成功") : Result.error("新增失败");
    }

    @Override
    public Result<PageBean<Article>> list(Integer pageNum, Integer pageSize, Integer categoryId, String state) {
        //开启分页
        PageHelper.startPage(pageNum, pageSize);
        //获取登录用户信息
        Map<String, Object> map = ThreadLocalUtil.get();
        //查询文章列表
        List<Article> list = articleMapper.list(categoryId, state,map.get("id").toString());
        //创建分页返回结果对象
        PageBean<Article> pageBean = new PageBean<>();
        pageBean.setItems(list);
        pageBean.setTotal((long) list.size());
        //返回结果
        return Result.success(pageBean);
    }

    @Override
    public Result get(Integer id) {
        return Result.success(articleMapper.findById(id));
    }

    @Override
    public Result update(Article article) {
        int i = articleMapper.update(article);
        return i > 0 ? Result.success("修改成功") : Result.error("修改失败");
    }

    @Override
    public Result delete(Integer id) {
        int i = articleMapper.delete(id);
        return i > 0 ? Result.success("删除成功") : Result.error("删除失败");
    }
}
